﻿using System;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Mixr
{
    public partial class MixrWindow : Form
    {
        //Variables representing the current user and the file they try to play by selecting it.
        int cur_id;
        string cur_user, cur_file;

        //Media control global control variables.
        bool playing = false;
        bool mediaLoaded = false;
        int playlistDummy = 1;

        //static string generate_delete_from_select; Used to generate a delete command but is not needed at the moment.

        //SQL objects used universally throughout all of the bleow operations
        static string connectionString
                = @"Data Source=.\SQLEXPRESS;AttachDbFilename='|DataDirectory|\UserDatabase.mdf';Integrated Security=True;User Instance=True";
        SqlDataAdapter dataAdapter = new SqlDataAdapter();
        DataTable cur_data = new DataTable();
        BindingSource bindingSource1 = new BindingSource();

        public MixrWindow(int uid, string uname) //Invoke the data finding sequence of methods when the window is loaded.
        {
            cur_id = uid;
            cur_user = uname;
            InitializeComponent();
        }

        private void GetSearchResults(string selectCommand) //Database is actually queried here.
        {
            //Create a new data table/set, then populate it with the matching results according to the SQL selectCommand
            cur_data = new DataTable();
            dataAdapter = new SqlDataAdapter(selectCommand, connectionString);
            dataAdapter.Fill(cur_data);
        }

        private void GetData(string selectCommand) //Binds the data from GetSearchResults to the GridView in the main window.
        {
            try
            {
                //Call GetSearchResults and actually get the data.
                GetSearchResults(selectCommand);
                bindingSource1.DataSource = cur_data;
                dataDisplay.DataSource = bindingSource1;

                //Make the data viewing location pretty, restricted, useful etc.
                //TO DO: ONLY ALLOW USER TO SELECT ONE CELL AT A TIME FROM THE FIRST COLUMN IN DATAGRIDVIEW. Is this possible>
                dataDisplay.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
                dataDisplay.AllowUserToAddRows = false;
                dataDisplay.AllowUserToDeleteRows = true;
                dataDisplay.AllowUserToResizeRows = false;
                dataDisplay.ReadOnly = true;
                dataDisplay.DefaultCellStyle.NullValue = "---";
                dataDisplay.DefaultCellStyle.WrapMode = DataGridViewTriState.True;
            }

            catch (SqlException)    //This will happen if either the query didn't work or the user has no data in that particular library.
            {
                MessageBox.Show("Either no data exists or something blew up.");
            }
        }

        private void dataDisplay_ColumnHeaderClick(object sender, DataGridViewCellEventArgs e)
        {
            //When the user clicks the heading of a column, then sort it.
            dataDisplay.Sort(dataDisplay.Columns[e.ColumnIndex], ListSortDirection.Ascending);
        }

        private void dataDisplay_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            //Rip the title of the piece of media that is selected in the datagridview.
            //THIS ASSUMES THE USER CAN SELECT ONLY ONE CELL IN THE FIRST COLUMN.
            DataGridViewCell cell = dataDisplay.SelectedCells[0];
            string media_title = cell.Value.ToString();
            string query = "";

            //Create a query for the rest of the data about that media based on the mode that the window is in.
            if (radioButtonMovies.Checked)
            {
                query =
                        "SELECT [Movie].Quality, [Movie].Rating, [Movie].Year, [Movie].Director, [Movie].Writer, [Movie].FileLoc, [Movie].Description, [Movie].Title FROM [Movie] WHERE UserID = " + cur_id + " AND [Movie].Title = '" + media_title + "'";
            }

            else if (radioButtonMusic.Checked)
            {
                query =
                        "SELECT [Music].Track, [Music].Genre, [Music].Year, [Music].Composer, [Music].FileLoc FROM [Music] WHERE UserID = " + cur_id + " AND [Music].Title = '" + media_title + "'";
            }

            else if (radioButtonTV.Checked)
            {
                query =
                        "SELECT [TV].Title, [TV].Actor, [TV].Year, [TV].Season, [TV].Episode, [TV].FileLoc FROM [TV] WHERE UserID = " + cur_id + " AND [TV].Title = '" + media_title + "'";
            }

            //generate_delete_from_select = query; See comment at variable declaration at beginning of code.

            //Try querying the database for that media, and then output the data to the controlbox in the main window.
            try
            {
                SqlConnection conn = new SqlConnection(connectionString);
                SqlCommand find_info = new SqlCommand(query, conn);
                conn.Open();

                SqlDataReader query_read = find_info.ExecuteReader();
                query_read.Read();
                
                //If the data doesn't exist, just blank the field.
                try{label1.Text = Convert.ToString(query_read[0]);}
                catch (Exception) { label1.Text = ""; }
                try{label2.Text = Convert.ToString(query_read[1]);}
                catch (Exception) { label2.Text = ""; }
                try{label3.Text = Convert.ToString(query_read[2]);}
                catch (Exception) { label3.Text = ""; }
                try{label4.Text = Convert.ToString(query_read[3]);}
                catch (Exception) { label4.Text = ""; }
                try{label5.Text = Convert.ToString(query_read[4]);}
                catch (Exception) { label5.Text = ""; }
                try { DescriptionLabel.Text = Convert.ToString(query_read[6]); }
                catch (Exception) { DescriptionLabel.Text = ""; }
                try { TitleLabel.Text = Convert.ToString(query_read[7]); }
                catch (Exception) { TitleLabel.Text = ""; }
                try { cur_file = Convert.ToString(query_read["FileLoc"]).Trim();}
                catch (Exception) { MessageBox.Show("Something went wrong. There is no file location associated with this piece of media."); }
            }

            //If nothing was found (shouldn't happen), throw an exception.
            catch (Exception)
            {
                label1.Text = "Select a title for more information.";
            }
        }

        private void MixrWindow_Load(object sender, EventArgs e)
        {
    
        }

        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            new AboutBox().Show();
        }

        private void addLocalMediaToolStripMenuItem_Click(object sender, EventArgs e)
        {
            new AddLocalMedia(cur_id, cur_user).Show();
        }

        private void aboutToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            new AboutBox().Show();
        }

        private void reScanLocalMediaToolStripMenuItem_Click(object sender, EventArgs e)
        {
            new AddLocalMedia(cur_id, cur_user).Show();
            this.Close();
        }

        private void radioButtonMusic_CheckedChanged(object sender, EventArgs e)
        {
            axVLC.CtlVisible = false;
            if (playing == true)
            {
                axVLC.playlist.stop();
                playing = false;
            }
            axVLC.playlist.items.clear();
            this.Height = 620;
            GetData("SELECT [Music].Title, [Music].Album, [Music].Artist FROM [Music] WHERE UserID = " + cur_id + "");
        }

        private void radioButtonMovies_CheckedChanged(object sender, EventArgs e)
        {
            axVLC.CtlVisible = true;
            if (playing == true)
            {
                axVLC.playlist.stop();
                playing = false;
            }
            axVLC.playlist.items.clear();
            this.Height = 890;
            GetData("SELECT [Movie].Title, [Movie].Genre, [Movie].Description FROM [Movie] WHERE UserID = " + cur_id + "");
        }

        private void radioButtonTV_CheckedChanged(object sender, EventArgs e)
        {
            axVLC.CtlVisible = true;
            if (playing == true)
            {
                axVLC.playlist.stop();
                playing = false;
            }
            axVLC.playlist.items.clear();
            this.Height = 890;
            GetData("SELECT [TV].* FROM [TV] WHERE UserID = " + cur_id + "");
        }

        private void quitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        //This algorithm will have to be improved over time, but it currently works as follows:
        //Check to make sure the DataGridView is populated (this is the purpose of the try/catch block).
        //Pick a random number between 0 and the maximum number of columns currently in the DataGridView control.
        //Once this column is picked, pick a random direction (ascending or descending).
        //Once these are both picked, sort!
        private void buttonBlend_Click(object sender, EventArgs e)
        {
            try
            {
                Random random_column = new Random();
                Random random_direction = new Random();

                int index = Convert.ToInt16(random_column.Next(dataDisplay.ColumnCount));
                int direction = Convert.ToInt16(random_direction.Next(2));
                if (direction == 1) dataDisplay.Sort(dataDisplay.Columns[index], ListSortDirection.Ascending);
                else dataDisplay.Sort(dataDisplay.Columns[index], ListSortDirection.Descending);
            }
            catch (Exception) {
                MessageBox.Show("Pick something, you don't blend air, do you?");
            }
        }

        private void buttonPlay_Click(object sender, EventArgs e)
        {
            if (mediaLoaded == false && playing == false)
            {
                buttonPlay.Text = "Pause";
                axVLC.playlist.items.clear();
                try
                { 
                    playlistDummy = axVLC.playlist.add(cur_file);
                    axVLC.playlist.playItem(playlistDummy);
                    this.Text = "Mixr - " + cur_file;
                    mediaLoaded = true;
                    playing = true;
                }

                catch (Exception) { MessageBox.Show("File doesn't exist!"); }
            }
            if (mediaLoaded == true && playing == true)
            {
                buttonPlay.Text = "Play";
                axVLC.playlist.togglePause();
                playing = false;
                return;
            }
            if (mediaLoaded == true && playing == false)
            {
                buttonPlay.Text = "Pause";
                axVLC.playlist.togglePause();
                playing = true;
                return;
            }
        }

        private void buttonStop_Click(object sender, EventArgs e)
        {
            buttonPlay.Text = "Play";
            axVLC.playlist.stop();
            playing = false;
            mediaLoaded = false;
        }

        private void buttonForward_Click(object sender, EventArgs e)
        {
            buttonPlay.Text = "Pause";
            if (playing == true)
                axVLC.playlist.stop();
            axVLC.playlist.items.clear();
            try
            {
                playlistDummy = axVLC.playlist.add(cur_file);
                axVLC.playlist.playItem(playlistDummy);
                mediaLoaded = true;
                playing = true;
            }
            catch (Exception) { MessageBox.Show("File doesn't exist!"); }
        }

        private void volumeBar_Scroll(object sender, EventArgs e)
        {
            axVLC.Volume = volumeBar.Value * 10;
        }

        //Deletes the row from the database when the row is deleted from the DataGridView control.
        //Unfortunately, currently still not working.
        //BUG: Every time the DataGridView control is cleared, I believe this function is called. This is an issue because then there is no string for the
        //SqlCommand initializer to create a command from. This causes an exception which crashes the application.

        /*
        private void dataDisplay_RowsRemoved(object sender, DataGridViewRowsRemovedEventArgs e)
        {
            SqlConnection conn = new SqlConnection(connectionString);
            dataAdapter.SelectCommand = new SqlCommand(generate_delete_from_select, conn);
            SqlCommandBuilder delete_CMD = new SqlCommandBuilder(dataAdapter);
            delete_CMD.GetUpdateCommand();
            delete_CMD.DataAdapter = dataAdapter;
            dataAdapter.Update(cur_data);
        }
         * */
    }
}
